import { ref } from 'vue'
import { ElMessage } from 'element-plus'

import { getParseRecordToken, getParseRecordMsg } from '@/api/record'

import { IRecordToken, IRecordMsg, IRecordFile, IRecordTokenResponse, IRecordMsgResponse } from '@/types/type'
declare global {
  interface Window { Recorder: any; }
}
window.Recorder = window.Recorder || {}

const useRecord = ():any => {
  // data 
  let rec: any
  const parseMsg = ref('')

  // methods
  // 请求录音权限
  const recOpen = (success: any) => {
    rec = window.Recorder({
      type: 'wav',
      sampleRate: 16000,
      bitRate: 16
    })

    rec.open(() => {
      success && success()
    }, (msg: string, isUserNotAllow: boolean) => {
      ElMessage({
        type: 'error',
        message: (isUserNotAllow ? 'UserNotAllow，' : '') + '无法录音:' + msg
      })
    })
  }

  const transformToPMC = (blob: Blob) => {
    blob.slice(44, blob.size, 'audio/pcm')
  }

  // const download = (blob: Blob) => {
  //   const link = document.createElement('a')
  //   link.style.display = 'none'
  //   link.href = (window.URL || window.webkitURL).createObjectURL(blob)
  //   link.setAttribute('download', 'record.pcm')
  //   document.body.appendChild(link)
  //   link.click()
  //   document.body.removeChild(link)
  // }
  
  const submit = (blob: Blob) => {
    const formData = new FormData()
    formData.append('file', blob, 'record.pcm')
    const recordTokenParams = {
      client_id: 'kVcnfD9iW2XVZSMaLMrtLYIz',
      client_secret: 'O9o1O213UgG5LFn0bDGNtoRN3VWl2du6',
      grant_type: 'client_credentials'
    }
    getParseRecordToken(recordTokenParams as IRecordToken).then((res: IRecordTokenResponse) => {
      console.log(res)
      const recordToken = res.refresh_token
      const recordParseParams = {
        dev_pid: '1537',
        cuid: '123456PHP',
        token: recordToken
      }
      getParseRecordMsg(recordParseParams as IRecordMsg, formData as any).then((res: IRecordMsgResponse) => {
        console.log(res)
        parseMsg.value = res.result[0] as any
      })
    })
  }
  // 开始录音
  const recStart = () => {
    // submit(blob)
    rec.start()
  }

  // 结束录音
  const recStop = () => {
    rec.stop((blob: Blob, duration: number) => {
      console.log(blob, (window.URL || window.webkitURL).createObjectURL(blob), '时长:' + duration + 'ms')
      rec.close()
      rec = null

      // 已经拿到blob文件对象想干嘛就干嘛：立即播放、上传。
      // const audio = document.createElement('audio')
      // audio.controls = true
      // document.body.appendChild(audio)
      // // 简单利用URL生成播放地址，注意不用了时需要revokeObjectURL，否则霸占内存
      // audio.src = (window.URL || window.webkitURL).createObjectURL(blob)
      // audio.play()

      // sl-转换格式
      transformToPMC(blob)

      // sl-下载pmc
      // download(blob)

      // sl-传给后端pmc
      submit(blob)
    }, (msg: string) => {
      ElMessage({
        type: 'error',
        message: '录音失败:' + msg
      })
      rec.close()
      rec = null
    })
  }

  return {
    recOpen,
    recStart,
    recStop,
    parseMsg
  }
}

export default useRecord
